package cn.chencq.gdt.utils;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import cn.chencq.gdt.vo.Gdt;

public final class GdtConfig {
	private static final Map<String, Gdt> CONTEXT_MAP = new HashMap<String, Gdt>();
	
	static{
		init("gdt.xml");
	}
	private GdtConfig() {
	}

	@SuppressWarnings("unchecked")
	public  static void init(String configFilePath) {
		SAXReader reader = new SAXReader();
		InputStream is = null;
		try {
			is= Gdt.class.getResourceAsStream("/"+configFilePath);
			if (is == null) {
				is = new FileInputStream(configFilePath);
			}
			Document doc = reader.read(is);
			Element root = doc.getRootElement();
			List<Element> ads = root.elements("ad");
			for (Element ad : ads) {
				List<Element> subs = ad.elements();
				Gdt gdt = new Gdt();
				for (Element sub : subs) {
					if("posid".equals(sub.getName())){
						gdt.setPosid(sub.getTextTrim());
					}else if("posttype".equals(sub.getName())){
						gdt.setPosttype(Integer.parseInt(sub.getTextTrim()));
					}else if("appid".equals(sub.getName())){
						gdt.setAppid(sub.getTextTrim());
					}else if("c_os".equals(sub.getName())){
						gdt.setC_os(sub.getTextTrim());
					}else if("muidtype".equals(sub.getName())){
						gdt.setMuidtype(Integer.parseInt(sub.getTextTrim()));
					}else if("c_packname".equals(sub.getName())){
						gdt.setC_packname(sub.getTextTrim());
					}
				}
				CONTEXT_MAP.put(gdt.getPosid(),gdt);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static Gdt getGdt(String posid) {
		return CONTEXT_MAP.get(posid);
	}

	public static List<Gdt> getList() {
		List<Gdt> glist = new ArrayList<Gdt>();
		for (String key : CONTEXT_MAP.keySet()) {
			glist.add(getGdt(key));
		}
		return glist;
	}
}
